﻿<%@ WebHandler Language="C#" Class="Assesment.Web.AjaxHandler.Administration.UserManagement.sRolehandler" %>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;

using Assesment.Library.DataAccess.Administration;
using Assesment.Library.DomainObject.Administration;
using Assesment.Library.DataAccess.Administration.UserManagement;
using Assesment.Library.DomainObject.Administration.UserManagement;

using Assesment.Library.Enum;
using Assesment.Web.Support;

using Newtonsoft.Json.Linq;

namespace Assesment.Web.AjaxHandler.Administration.UserManagement
{
    public class sRolehandler : Assesment.Web.BaseHandler
    {

        private recRoleRepo roleDal = new recRoleRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
        private recUserRepo userDal = new recUserRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
        private recLogRepo logDal = new recLogRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
        private string MethodName = string.Empty;


        public override void ProcessRequest(HttpContext context)
        {

            base.ProcessRequest(context);

            MethodName = context.Request.Params["method"];

            context.Response.Clear();
            context.Response.Buffer = true;

            System.IO.StreamReader sr = new System.IO.StreamReader(context.Request.InputStream);

            string jsonString = string.Empty;
            jsonString = context.Server.UrlDecode(sr.ReadToEnd());
            JObject jObj = string.IsNullOrEmpty(jsonString) ? null : JObject.Parse(jsonString);

            sr.Close();
            sr.Dispose();

            switch (MethodName.ToLower())
            {
                case ("insert"):
                    context.Response.Write(Insert(context, jObj));
                    break;
                case ("update"):
                    context.Response.Write(Update(context, jObj));
                    break;
                case ("delete"):
                    context.Response.Write(Delete(context, jObj));
                    break;
                //case ("getdatainternal"):
                //    context.Response.Write(GetDataInternal(context));
                //    break;
                //case ("getdataexternal"):
                //    context.Response.Write(GetDataExternal(context));
                //    break;
                case ("getdata"):
                    context.Response.Write(GetData(context));
                    break;
                default:
                    // do nothing
                    break;
            }

            context.Response.Flush();
            context.Response.End();
        }

        public override bool IsReusable
        {
            get
            {
                return false;
            }
        }

        private string Insert(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recRole obj = new recRole();
                int status = (int)jo["Status"];
                obj.RoleName = (string)jo["RoleName"];
                obj.CreatedDate = DateTime.Now;
                obj.CreatedBy = base.UserLoggedIn;

                if (status == -1)
                    obj.IsInternal = true;
                else
                    obj.IsInternal = false;

                roleDal.Save(obj);

                helper.Message = "Data berhasil di simpan !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Insert";
                log.LogMessage = helper.Message;
                log.LogSource = "sRolehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string GetData(HttpContext context)
        {
            JSONHelper helper = new JSONHelper();
            string Isinternal = context.Request.Params["UserID"];
            string parameters = Helper.JqGridFilterToSQLParams(context);
            
            int page = 1;
            int.TryParse(context.Request.QueryString["page"] ?? "1", out page);

            int pageSize = 10;
            int.TryParse(context.Request.QueryString["rows"] ?? "10", out pageSize);

            string sidx = ((context.Request.QueryString["sidx"]) == null ? recRole.Fields.RoleName : context.Request.QueryString["sidx"].ToString());

            string sord = ((context.Request.QueryString["sord"]) == null ? "ASC" : context.Request.QueryString["sord"].ToString());

            int totalCount = 0;
            int totalPages = 0;
            List<recRole> pagedList = null;

            try
            {
                totalCount = Convert.ToInt32(roleDal.SelectScalar(SQL.Function.Aggregate.Count, recRole.Fields.RoleID, parameters));

                decimal dc = decimal.Ceiling(Convert.ToDecimal(totalCount) / Convert.ToDecimal(pageSize));
                totalPages = Convert.ToInt32(dc);

                pagedList = roleDal.GetList(pageSize, page, sidx, sord, parameters);
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "GetData";
                log.LogMessage = helper.Message;
                log.LogSource = "sRolehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
                log.Dispose();
            }

            // send params into jqGrid's format
            var gridData = new
            {
                page = page,
                total = totalPages,
                records = totalCount,
                rows = pagedList,
            };

            return Newtonsoft.Json.JsonConvert.SerializeObject(gridData);

        }

        private string Update(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();

            try
            {
                recRole obj = new recRole();
                short status = (short)jo["Status"];
                obj.RoleID = Convert.ToInt32(jo["RoleID"]);
                obj.RoleName = (string)jo["RoleName"];
                obj.UpdatedDate = DateTime.Now;
                obj.UpdatedBy = base.UserLoggedIn;

                if (status == -1)
                    obj.IsInternal = true;
                else
                    obj.IsInternal = false;

                roleDal.Update(obj);

                helper.Message = "Data berhasil di ubah !";
                helper.IsSuccess = true;
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Update";
                log.LogMessage = helper.Message;
                log.LogSource = "sRolehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);
            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

        private string Delete(HttpContext context, JObject jo)
        {
            JSONHelper helper = new JSONHelper();
            recUserRoleRepo userRoleDal = new recUserRoleRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);
            recMenuRightsRepo menuRighstDal = new recMenuRightsRepo(ConfigurationManager.ConnectionStrings["AssesmentConn"].ConnectionString);

            try
            {
                var strId = (string)jo["RoleID"];

                string[] ids = strId.Split(',');
                List<int> idCantBeDeleted = new List<int>();

                foreach (string id in ids)
                {
                    int roleId = Convert.ToInt32(id);
                    var users = userRoleDal.GetListByRoleID(roleId); // Check RoleID in recUserRole table.
                    if (users.Count > 0)
                        idCantBeDeleted.Add(roleId);

                }

                var menus = menuRighstDal.GetList().FindAll(x => ids.Contains(x.RoleID.ToString())); // Check RoleID in recMenuRights table.
                menus.ForEach(delegate(recMenuRights mnRight)
                {
                    idCantBeDeleted.Add(mnRight.RoleID);
                });

                var DistinctCantBeDeletedIds = idCantBeDeleted.Distinct();

                foreach (string id in ids)
                {
                    int roleId = Convert.ToInt32(id);
                    var idx = DistinctCantBeDeletedIds.Where(x => x.Equals(roleId));
                    if (idx.Count() == 0)
                    {
                        roleDal.Delete(roleId);
                        helper.IsSuccess = true;
                    }
                    else
                        helper.IsSuccess = false;
                }

                string roleName = string.Empty;
                foreach (var objId in DistinctCantBeDeletedIds)
                {
                    roleName += roleDal.GetById(objId).RoleName + ",";                
                }

                if (!string.IsNullOrEmpty(roleName))
                {
                    roleName = Helper.String.Left(roleName, roleName.Length - 1);
                    helper.Message = roleName + " tidak bisa di hapus karena ada relasi ditempat lain!";
                }
                else
                    helper.Message = "Data berhasil di hapus !";
                
            }
            catch (Exception ex)
            {
                helper.IsSuccess = false;
                helper.Message = ex.Message;
            }
            finally
            {
                recLog log = new recLog();
                log.LogEvent = "Delete";
                log.LogMessage = helper.Message;
                log.LogSource = "sRolehandler.ashx";
                log.CreatedBy = base.UserLoggedIn;
                log.CreatedDate = DateTime.Now;
                logDal.Save(log);

            }

            return Newtonsoft.Json.JsonConvert.SerializeObject(helper);

        }

      

    }

}